// 创建一个格式化器，指定语言环境和选项
const formatter = new Intl.DateTimeFormat("zh-CN", {
  year: "numeric",
  month: "2-digit",
  day: "2-digit",
  hour: "2-digit",
  minute: "2-digit",
  second: "2-digit",
  hour12: false, // 使用24小时制
  timeZone: "Asia/Shanghai", // 指定时区，这里使用了上海时区
});
const formatDate = (date: string | number | Date | undefined) => {
  return date ? formatter.format(new Date(date)) : date;
};
// 创建一个将list转为tree的函数,对象为any
const listToTree = (list: any[], parentId: number | null = 0, parentKey: string = "parent") => {
  // Create a map to store items by their IDs for O(1) lookup
  const itemMap = new Map();
  const tree: any[] = [];

  // First pass: create a map of all items
  for (const item of list) {
    // Create a shallow copy to avoid mutating the original object
    itemMap.set(item.id, { ...item });
  }

  // Second pass: build the tree structure
  for (const item of itemMap.values()) {
    const parentItem = itemMap.get(item[parentKey]);

    if (item[parentKey] === parentId) {
      // Root level items
      tree.push(item);
    } else if (parentItem) {
      // Add as child to parent
      if (!parentItem.children) {
        parentItem.children = [];
      }
      parentItem.children.push(item);
    }
  }

  return tree;
};

export { formatDate, listToTree };
